<?php
/**
 * CreateTime: 2024/1/8 19:30
 * User:LinQ
 */

namespace App\Console\Commands;

use App\Factory\Email\NetEaseEmailSender;
use App\Jobs\LetterFileJob;
use App\Models\Zb\DiffModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;

class ZbDiffJumpShopCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:zbDiffShop';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function compareArrays($array2,$array1)
    {
        $difference = [];
        foreach ($array1 as $item1) {
            $found = false;
            foreach ($array2 as $item2) {
                if ($item1 == $item2) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {

                $difference[] = $item1;
            }
        }
        return $difference;
    }


    /**
     * Execute the console command.
     * 这个方法中的逻辑需要自己写
     * @return mixed
     */
    public function handle()
    {
        $zbDiffModel = new DiffModel();
        $wyEmail = new NetEaseEmailSender();
        while(true){
            date_default_timezone_set('Asia/Tokyo');
            echo "任务开始\n";
            try {
                $process = new Process(['python3',app_path().DIRECTORY_SEPARATOR.'Python'.DIRECTORY_SEPARATOR.'getJumpshop.py']);
                $process->run();
                $r = $process->getOutput();
                if($r){
                    $fmtR = json_decode(trim($r,"\n"),true)['products'];
                    $aesEncode = aes_256_cbc_pkcs7_encode(json_encode($fmtR,256));
//                    $aesEncode = aes_256_cbc_pkcs7_encode('[{"id":7927545266384,"gid":"gid:\/\/shopify\/Product\/7927545266384","vendor":"『鬼滅の刃』","type":"","variants":[{"id":43541249753296,"price":198000,"name":"鬼滅の刃　衣装モチーフキーホルダー　煉󠄁999999999獄杏寿郎","public_title":null,"sku":"46476"}]},{"id":6808876187856,"gid":"gid:\/\/shopify\/Product\/6808876187856","vendor":"『鬼滅の刃』","type":"","variants":[{"id":40375725981904,"price":297000,"name":"鬼滅の刃　伊之助のかぶりもの","public_title":null,"sku":"35957"}]},{"id":7911229292752,"gid":"gid:\/\/shopify\/Product\/7911229292752","vendor":"『呪術廻戦』","type":"","variants":[{"id":43456159252688,"price":198000,"name":"呪術廻戦　懐玉・玉折　2023　箔アクリルスタンド　五条悟","public_title":null,"sku":"46243"}]},{"id":7911229325520,"gid":"gid:\/\/shopify\/Product\/7911229325520","vendor":"『呪術廻戦』","type":"","variants":[{"id":43456159285456,"price":198000,"name":"呪術廻戦　懐玉・玉折　2023　箔アクリルスタンド　夏油傑","public_title":null,"sku":"46244"}]},{"id":7911229653200,"gid":"gid:\/\/shopify\/Product\/7911229653200","vendor":"『呪術廻戦』","type":"","variants":[{"id":43456159645904,"price":341000,"name":"呪術廻戦　懐玉・玉折 どんぶり","public_title":null,"sku":"46262"}]},{"id":7332088971472,"gid":"gid:\/\/shopify\/Product\/7332088971472","vendor":"『呪術廻戦』","type":"","variants":[{"id":42067178356944,"price":132000,"name":"『呪術廻戦』アルファベットマグ“Ｙ”　虎杖悠仁　","public_title":null,"sku":"18046463"}]},{"id":7332089004240,"gid":"gid:\/\/shopify\/Product\/7332089004240","vendor":"『呪術廻戦』","type":"","variants":[{"id":42067178389712,"price":132000,"name":"『呪術廻戦』アルファベットマグ“Ｍ”　伏黒恵　","public_title":null,"sku":"18046464"}]},{"id":6808880120016,"gid":"gid:\/\/shopify\/Product\/6808880120016","vendor":"『呪術廻戦』","type":"","variants":[{"id":40375751999696,"price":396000,"name":"呪術廻戦　ほぼ等身大呪骸ぬいぐるみ（ツカモト）","public_title":null,"sku":"37860"}]},{"id":6808941002960,"gid":"gid:\/\/shopify\/Product\/6808941002960","vendor":"『呪術廻戦』","type":"","variants":[{"id":40375994482896,"price":198000,"name":"呪術廻戦　ツカモト　ボールチェーンマスコット　眠り顔ver.","public_title":null,"sku":"38894"}]},{"id":6808941330640,"gid":"gid:\/\/shopify\/Product\/6808941330640","vendor":"『呪術廻戦』","type":"","variants":[{"id":40375994974416,"price":198000,"name":"呪術廻戦　ツカモト　ボールチェーンマスコット　怒り顔ver.","public_title":null,"sku":"38895"}]},{"id":7741563863248,"gid":"gid:\/\/shopify\/Product\/7741563863248","vendor":"『呪術廻戦』","type":"","variants":[{"id":42857704063184,"price":99000,"name":"呪術廻戦 ジャガードハンドタオル 玉犬","public_title":null,"sku":"43341"}]},{"id":6808901353680,"gid":"gid:\/\/shopify\/Product\/6808901353680","vendor":"『ハイキュー!!』","type":"","variants":[{"id":40375832707280,"price":55000,"name":"『ハイキュー!!』アンブレラチャームコレクション（全１９種）","public_title":null,"sku":"18042171"}]},{"id":6856866857168,"gid":"gid:\/\/shopify\/Product\/6856866857168","vendor":"『ハイキュー!!』","type":"","variants":[{"id":40536749801680,"price":88000,"name":"『ハイキュー!!』及川の「全員倒す」ドミノ風アクリルキーホルダーコレクション　（全11種＋シークレット1種）","public_title":null,"sku":"18045919"}]},{"id":7741563896016,"gid":"gid:\/\/shopify\/Product\/7741563896016","vendor":"『ハイキュー!!』","type":"","variants":[{"id":42857704095952,"price":99000,"name":"ハイキュー!! ジャガードハンドタオル 烏野&稲荷崎","public_title":null,"sku":"43342"}]},{"id":7741563928784,"gid":"gid:\/\/shopify\/Product\/7741563928784","vendor":"『ハイキュー!!』","type":"","variants":[{"id":42857704128720,"price":99000,"name":"ハイキュー!! ジャガードハンドタオル 音駒&梟谷学園","public_title":null,"sku":"43343"}]},{"id":7837360619728,"gid":"gid:\/\/shopify\/Product\/7837360619728","vendor":"『チェンソーマン』","type":"","variants":[{"id":43171083616464,"price":396000,"name":"チェンソーマン ポチタのティッシュカバー","public_title":null,"sku":"44843"}]},{"id":7741563961552,"gid":"gid:\/\/shopify\/Product\/7741563961552","vendor":"『ONE PIECE』","type":"","variants":[{"id":42857704161488,"price":99000,"name":"ONE PIECE ジャガードハンドタオル 兄弟","public_title":null,"sku":"43344"}]}]');
                    $hash = md5($aesEncode);
                    echo "时间".date('Y-m-d h:i.s')."\n";
                    echo json_encode($fmtR,256)."\n";
                    echo $hash."\n";
                    echo "---------------------------------";
                    $isExists = $zbDiffModel->where('hash',$hash)->where('diff_id',1)->first();
                    if(!$isExists){
                        $default =  $zbDiffModel->where('diff_id',1)->first();
                        $defaultStr = json_decode(aes_256_cbc_pkcs7_decode($default['str']),true);
                        $aesDefaultStr = aes_256_cbc_pkcs7_encode(json_encode($defaultStr,256));
                        $diffArray = $this->compareArrays($defaultStr ?? [],$fmtR);
                        $str = '<div>尊敬的客户，您好！</div>
<div style="margin-top:12px">
    <span style="font-weight: bold;">感谢您订阅我们的服务。</span>我很高兴地告诉您，您订阅的<span style="font-weight: bold;color: red">《JumpShop-咒术回战商品》</span>已经更新了。<br>
</div>
<div style="margin-top:12px">
  <a href="https://jumpshop-online.com/collections/%E5%86%8D%E5%85%A5%E8%8D%B7%E3%82%A2%E3%82%A4%E3%83%86%E3%83%A0?filter.v.price.gte=&filter.v.price.lte=&sort_by=manual">点击前往JumpShop查看更新信息</a>
</div>
<div style="margin-top:12px">
    以下是商品更新情况，请您查阅：
</div>
<div style="margin:24px 12px;padding:24px;background-color: #F4F7FC;border-radius: 24px;box-shadow: 0 2px 10px 2px rgba(0, 0, 0, 0.1);">';
                        foreach($diffArray as $value){
                            $str .= '<div>
        <div style="font-weight: bold;">'.$value['vendor'].'</div>
        <div style="padding-left: 12px;margin-top: 12px;">
            <table style="border-collapse: collapse;font-size: 12px;background-color: #fff;">
                <thead>
                    <th style="border: 1px solid black; padding: 4px;">商品SKU</th>
                    <th style="border: 1px solid black; padding: 4px;">商品名称</th>
                    <th style="border: 1px solid black; padding: 4px;">价格</th>
                    <th style="border: 1px solid black; padding: 4px;">更新时间</th>
                </thead>';
                            foreach($value['variants'] as $vv){
                                $str.= '<tr>
                    <td style="border: 1px solid black; padding: 4px;">'.$vv['sku'].'</td>
                    <td style="border: 1px solid black; padding: 4px;">'.$vv['name'].'</td>
                    <td style="border: 1px solid black; padding: 4px;">¥'.($vv['price']/100).'</td>
                    <td style="border: 1px solid black; padding: 4px;">'.date("Y-m-d h:i:s").'</td>
                </tr>';
                            }
                            $str.='</table></div></div><div style="height: 24px;width: 100%;"></div>';
                        }
                        $str.= '</div><div style="font-size: 12px;margin-top:36px">
    <div style="margin-top:12px">
       如果您有任何疑问或建议，请随时联系我们，我们将竭诚为您提供更好的服务。
    </div>
   <div style="margin-top:12px">
    <strong style="color: #EA4E3E;">Copyright © 2023 枫痕科技 MapleDigits</strong>
   </div>
</div>';
                        $wyEmail->sendEmail(
                            'xy219319@yahoo.co.jp','您订阅的价格变化有更新了！',$str
                        );
                        $wyEmail->sendEmail(
                            '2480568306@qq.com','您订阅的价格变化有更新了！',$str
                        );


                        $zbDiffModel->where('diff_id',1)->update([
                            'str' => $aesEncode,
                            'hash' => $hash
                        ]);
                        $zbDiffModel->where('diff_id',2)->update([
                            'str' => $aesDefaultStr,
                            'hash' => $default['hash']
                        ]);
                        // 发送邮件
                        echo "任务结束 ".date('Y-m-d h:i:s');
                    }
                }
            }catch (\Exception $exception){
                dump(json_encode([
                    'created_time' => date("Y-m-d h:i:s"),
                    'title' => "shopError",
                    'ex' => $exception->getMessage()
                ]));
            }
//            sleep(20);
            sleep(rand(120,160));
//            die();
        }
    }
}
